﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace NFinal.Common.TaskLogger
{
    public class ConsoleTaskLogger : ITaskLogger
    {
        public string Name { get; }
        public CancellationToken CancellationToken { get; }
        private CancellationTokenSource CancellationTokenSource { get; }
        public ConsoleTaskLogger(string name=null)
        {
            this.CancellationTokenSource = new CancellationTokenSource();
            this.CancellationToken = CancellationTokenSource.Token;
            if (name == null)
            {
                Name = "任务";
            }
            else
            {
                Name = name;
            }
        }

        public void LogInfo(string message)
        {
            Console.WriteLine(message);
        }
        public void LogError(string error)
        {
            Console.WriteLine(error);
        }
        public void LogExp(Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
        }
        public void LogWarn(string warn)
        {
            Console.WriteLine(warn);
        }
        public bool init = false;
        public void LogPercentage(double percentage, string name = null)
        {
            if (name == null)
            {
                name = Name;
            }
            if (init == false)
            {
                init = true;
                Console.WriteLine($"{name}进度:{Math.Round(percentage, 2)}%");
            }
            if (percentage == 100)
            {
                int currentLineCursor = Console.CursorTop;//记录当前光标位置
                Console.SetCursorPosition(0, currentLineCursor - 1);//将光标至于当前行的开始位置
                Console.Write(new string(' ', Console.WindowWidth));//用空格将当前行填满，相当于清除当前行
                Console.SetCursorPosition(0, currentLineCursor - 1);//将光标恢复至开始时的位置
                Console.WriteLine($"{name}进度:{Math.Round(percentage, 2)}%");
                init = false;
            }
            if (init)
            {
                int currentLineCursor = Console.CursorTop;//记录当前光标位置
                Console.SetCursorPosition(0, currentLineCursor - 1);//将光标至于当前行的开始位置
                Console.Write(new string(' ', Console.WindowWidth));//用空格将当前行填满，相当于清除当前行
                Console.SetCursorPosition(0, currentLineCursor -1);//将光标恢复至开始时的位置
                Console.WriteLine($"{name}进度:{Math.Round(percentage, 2)}%");
            }
        }

        public void LogExp(Exception ex, string message)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine(message);
        }

        public bool CancelCurrentTask()
        {
            this.CancellationTokenSource.Cancel();
            return true;
        }
    }
}
